package com.android.aishangauction.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.aishangauction.R;
import com.android.aishangauction.activity.mine.PaySuccessActivity;
import com.android.aishangauction.activity.mine.TakeOverAddressActivity;
import com.android.aishangauction.app.BaseActivity;
import com.android.aishangauction.fragment.member.Fragment_Mine_DirectBuy_Order;
import com.android.aishangauction.model.MainTabData;
import com.android.aishangauction.model.detail.AuctionDetailPreData;
import com.android.aishangauction.model.detail.AuctionDetailPreDataCallback;
import com.android.aishangauction.model.detail.AuctionOrderDetailData;
import com.android.aishangauction.model.detail.AuctionOrderDetailDataCallback;
import com.android.aishangauction.model.detail.DirectBuyAliPayData;
import com.android.aishangauction.model.detail.DirectBuyAliPayDataCallback;
import com.android.aishangauction.model.detail.DirectBuyOrderPayMethodData;
import com.android.aishangauction.model.detail.DirectBuyWXPayData;
import com.android.aishangauction.model.detail.DirectBuyWXPayDataCallback;
import com.android.aishangauction.model.group.FlowPaymentData;
import com.android.aishangauction.model.group.FlowPaymentDataCallback;
import com.android.aishangauction.model.member.AddressListData;
import com.android.aishangauction.model.member.AddressListDataCallback;
import com.android.aishangauction.utils.ConstantsUrl;
import com.android.aishangauction.utils.HttpUtils;
import com.android.aishangauction.utils.MyLog;
import com.android.aishangauction.utils.ObjectUtils;
import com.android.aishangauction.utils.alipay.PayResult;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/9/28.
 */

public class AuctioningPayOrderActivity extends BaseActivity {
    @BindView(R.id.address_add_ll)
    LinearLayout address_add_ll;
    @BindView(R.id.address_ll)
    LinearLayout address_ll;
    @BindView(R.id.address_name)
    TextView addressName;
    @BindView(R.id.address_address)
    TextView addressAddress;
    @BindView(R.id.order_number_tv)
    TextView orderNumber;
    @BindView(R.id.goods_img)
    ImageView goodsImg;
    @BindView(R.id.goods_title)
    TextView goodsTitle;
    @BindView(R.id.bargain_money)
    TextView bargain_money;
    @BindView(R.id.goods_price)
    TextView goods_price;
    @BindView(R.id.real_money)
    TextView treal_money;
    @BindView(R.id.pay_style)
    TextView pay_style;
    @BindView(R.id.pay_style_tv)
    TextView pay_style_tv;
    @BindView(R.id.order_express_name)
    TextView order_express_name;
    @BindView(R.id.order_express_num)
    TextView order_express_num;
    @BindView(R.id.ll_express)
    LinearLayout ll_express;
    @BindView(R.id.bottom_buy)
    Button bottom_buy;
    @BindView(R.id.pay_style_list)
    NestFullListView pay_style_list;
    @BindView(R.id.order_status_tv)
    TextView order_status_tv;
    @BindView(R.id.order_status_ll)
    LinearLayout order_status_ll;
    @BindView(R.id.order_status)
    TextView order_status;
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    private boolean networkConnected;
    private AuctioningPayOrderActivity mcontext;
    private String order_id;
    private String address_id;
    private List<DirectBuyOrderPayMethodData.DataBean.PaymentBean> payment = new ArrayList<>();
    private ArrayList<FlowPaymentData.DataBean.PaymentBean> listdata = new ArrayList<>();


    private ArrayList<MainTabData> mSortListdata = new ArrayList<>();
    private boolean isclick=false;
    private int pospay=100;
    private String pay_id;
    private String pay_name ="";
    private String order_sn;
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mcontext, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent mIntent = new Intent(Fragment_Mine_DirectBuy_Order.DIRECTBUY_ORDER_PAY);
                        mcontext.sendBroadcast(mIntent);
                        toPaySuccess();
                        finish();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000") || TextUtils.equals(resultStatus, "6004")) {
                            ObjectUtils.toast(mcontext, "支付结果确认中");
                        }
                        else if (TextUtils.equals(resultStatus, "6001")) {
                            ObjectUtils.toast(mcontext, "支付取消");
//                            toPaySuccess();
//                            finish();
                        }
                        else if (TextUtils.equals(resultStatus, "6002")) {
                            ObjectUtils.toast(mcontext, "网络异常");
                        }
                        else if (TextUtils.equals(resultStatus, "5000")) {
                            ObjectUtils.toast(mcontext, "重复请求");
                        }
                        else {
                            // 其他值就可以判断为支付失败
                            ObjectUtils.toast(mcontext, "支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void toPaySuccess() {
        Intent intent = new Intent(this, PaySuccessActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auctioning_payorder);
        ButterKnife.bind(this);
        mcontext = AuctioningPayOrderActivity.this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initTitle(0, "订单详情");
        initUI();
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
        GetDataListData();
        GetDetail();
        GetDataOrder();
    }

    @OnClick({R.id.bottom_buy,R.id.address_add_ll,R.id.address_ll
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bottom_buy:
                if(pay_name.equals("")||pay_name==null)
                {
                    ObjectUtils.toast(mcontext,"请选取支付方式");
                    return;
                }
                toPay();
                break;
            case R.id.address_add_ll:
                Intent intent_address = new Intent(this, TakeOverAddressActivity.class);
                startActivityForResult(intent_address,0);
                break;
            case R.id.address_ll:
                Intent intent_address1 = new Intent(this, TakeOverAddressActivity.class);
                startActivityForResult(intent_address1,0);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // 根据上面发送过去的请求吗来区别
        switch (requestCode) {
            case 0:
                GetDataListData();
                break;
            default:
                break;
        }
    }

    private void initUI() {
        order_id = getIntent().getStringExtra("order_id");
        address_id =getIntent().getStringExtra("address_id");
        pay_style_list.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int position) {
                if(!isclick)
                {
                    bottom_buy.setClickable(true);
                    bottom_buy.setBackgroundResource(R.drawable.corner_red_bg_selector);
                    isclick=true;
                }
                pospay = position;
                pay_id=mSortListdata.get(position).getId();
                pay_name = mSortListdata.get(position).getName();
                nestFullListView.updateUI();
                PreparePay();
            }
        });
    }
    //获取地址列表数据
    private void GetDataListData() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERADDRESSLIST;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.get(address, header, null, new AddressListDataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            address_add_ll.setVisibility(View.VISIBLE);
                            address_ll.setVisibility(View.GONE);
                            ObjectUtils.toast(mcontext, "没有默认地址");
                        }

                        @Override
                        public void onResponse(AddressListData response, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                            if (response.getCode() == 0) {
                                List<AddressListData.AddressData> data = response.getData();
                                if (data != null && data.size() > 0) {
                                    address_add_ll.setVisibility(View.GONE);
                                    address_ll.setVisibility(View.VISIBLE);
                                    for(int i = 0; i< data.size(); i++)
                                    {
                                        if(data.get(i).getIs_default().equals("1"))
                                        {
                                            address_id = data.get(i).getId();
                                            if(data.get(i).getName()!=null)
                                            {
                                                addressName.setText(data.get(i).getName());
                                            }
                                            if(data.get(i).getAddress()!=null)
                                            {
                                                addressAddress.setText(data.get(i).getAddress());
                                            }
                                            break;
                                        }
                                    }
                                } else {
                                    address_add_ll.setVisibility(View.VISIBLE);
                                    address_ll.setVisibility(View.GONE);
                                    ObjectUtils.toast(mcontext, "没有默认地址");
                                }
                            } else {
                                if(response.getCode() == 40001){
                                    ObjectUtils.reLogin(mcontext);
                                }
                                address_add_ll.setVisibility(View.VISIBLE);
                                address_ll.setVisibility(View.GONE);
                                ObjectUtils.toast(mcontext, "没有默认地址");
                            }

                        }
                    }

            );
        } else {
            address_add_ll.setVisibility(View.VISIBLE);
            address_ll.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, "没有默认地址");
        }
    }

    //获取详情
    private void GetDetail() {
        String address = ConstantsUrl.domain + ConstantsUrl.AUCTIONORDERDETAIL;
        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("order_id",order_id);
            HttpUtils.get(address, header,  map, Callback);
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    private AuctionOrderDetailData.DataBean responseData;
    AuctionOrderDetailDataCallback Callback = new AuctionOrderDetailDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.toast(mcontext,e.getMessage());
        }

        @Override
        public void onResponse(AuctionOrderDetailData response, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            if(response.getCode()==0)
            {
//                address_id = response.getData().getAddress_id();
//
//                if(response.getData().getAddress()==null) {
//                    address_add_ll.setVisibility(View.VISIBLE);
//                    address_ll.setVisibility(View.GONE);
//                }else
//                {
//                    if (response.getData().getAddress().equals("")) {
//                        address_add_ll.setVisibility(View.VISIBLE);
//                        address_ll.setVisibility(View.GONE);
//                    } else {
//                        address_add_ll.setVisibility(View.GONE);
//                        address_ll.setVisibility(View.VISIBLE);
//                    }
//                }
//                if(response.getData().getReceive_name()!=null)
//                {
//                    addressName.setText(response.getData().getReceive_name());
//                }
//                if(response.getData().getAddress()!=null)
//                {
//                    addressAddress.setText(response.getData().getAddress());
//                }
                responseData = response.getData();
                if(responseData.getOrder_sn()!=null)
                {
                    orderNumber.setText(responseData.getOrder_sn());
                }
                if(responseData.getThumb()!=null)
                {
                    ObjectUtils.photo2(mcontext, responseData.getThumb() ,goodsImg);
                }
                if(responseData.getTitle()!=null)
                {
                    goodsTitle.setText(responseData.getTitle());
                }
                if(responseData.getPrice()!=null)
                {
                    bargain_money.setText(responseData.getPrice());
                }
                if(responseData.getMarket_price()!=null)
                {
                    goods_price.setText(responseData.getMarket_price());
                }
                if(responseData.getPrice()!=null)
                {
                    treal_money.setText(responseData.getPrice());
                }
                DealwithMessage(responseData.getOrder_code(), responseData.getPay_name());
            }
            else {
                ObjectUtils.toast(mcontext, response.getMsg());
            }
        }
    };
    //处理不同订单详情
    private void DealwithMessage(int type,String pay_name) {
        switch (type)
        {
            case 1:
                pay_style.setVisibility(View.INVISIBLE);
                break;
            case 2:
                pay_style.setVisibility(View.INVISIBLE);
                break;
            default:
                address_add_ll.setVisibility(View.GONE);
                address_ll.setVisibility(View.GONE);
                pay_style_tv.setText("支付方式");
                pay_style.setText(pay_name);
                pay_style_list.setVisibility(View.GONE);
                bottom_buy.setVisibility(View.GONE);
                order_status_tv.setVisibility(View.VISIBLE);
                order_status_ll.setVisibility(View.VISIBLE);
                switch (type)
                {
                    case 3:
                        order_status.setText("待发货");
                        break;
                    case 4:
                        order_status.setText("待收货");
                        showExpress();
                        break;
                    case 5:
                        order_status.setText("待评论");
                        showExpress();
                        break;
                    case 6:
                        order_status.setText("已关闭");
                        break;
                    case 7:
                        order_status.setText("已收货，已评论");
                        showExpress();
                        break;
                    case 8:
                        order_status.setText("发货超过14天，已自动收货");
                        showExpress();
                        break;
                    case 9:
                        order_status.setText("超过领取时限,已失效");
                        break;
                    case 10:
                        order_status.setText("未到保底价，活动不成立");
                        break;
                }

                break;
        }

    }

    private void showExpress() {
        ll_express.setVisibility(View.VISIBLE);
        order_express_name.setText(responseData.getExpress_name());
        order_express_num.setText(responseData.getExpress_num());
    }

    //获取支付方式详情
    private void GetDataOrder() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.FLOWPAYMENT ;

        MyLog.e("地址", address);
        if (networkConnected) {
            HttpUtils.get(address,  null, new FlowPaymentDataCallback() {


                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.toast(mcontext, "没有获取到支付方式");
                }

                @Override
                public void onResponse(FlowPaymentData response, int id) {
                    if (response.getCode() == 0 && response.getData() != null) {
                        listdata.addAll(response.getData().getPayment());
                        //支付方式
                        mSortListdata.clear();
                        for (int i = 0; i < listdata.size(); i++) {
                            String  pay_id = listdata.get(i).getPay_id() ;
                            if (listdata.get(i).getPay_code().equals("wxpayapp")) {
                                mSortListdata.add(new MainTabData("微信",pay_id , R.mipmap.support_pay_wx));
                            }
                            if (listdata.get(i).getPay_code().equals("alipayapp")) {
                                mSortListdata.add(new MainTabData("支付宝", pay_id , R.mipmap.support_pay_ali));
                            }
                        }
                        if(listdata.size()>0) {
                            pay_id = listdata.get(0).getPay_id();
                        }

                        //        mSortListdata.add(new MainTabData("银联(未开通)", "", R.mipmap.support_pay_yl));
                        pay_style_list.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_pay, mSortListdata) {
                            @Override
                            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                                holder.setText(R.id.pay_name, testBean.getName());
                                holder.setImageResource(R.id.pay_logo, testBean.getThumb());
                                if (pospay == position) {//最后选择的位置
                                    holder.setChecked(R.id.item_list_mine_pay_check, true);
                                } else {
                                    holder.setChecked(R.id.item_list_mine_pay_check, false);
                                }
                            }
                        });
                        pay_style_list.updateUI();
                    } else {
                        ObjectUtils.toast(mcontext, "没有获取到支付方式");
                    }


                }
            });
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }
    private void PreparePay() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.AUCTIONCHECKOUT;
        HashMap<String, String> map = new HashMap<>();
        map.put("pay_id", pay_id + "");
        map.put("order_id", order_id);
        map.put("address_id", address_id);
        map.put("pre","1");
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.post(address, header,map,preDataCallback);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    AuctionDetailPreDataCallback preDataCallback = new AuctionDetailPreDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(AuctionDetailPreData response, int id) {
            if(response.getCode()==0){
                ObjectUtils.toast(mcontext, "选择成功");
            }
            else
            {
                ObjectUtils.toast(mcontext, response.getMsg());
            }
        }
    };


    private void toPay() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.AUCTIONCHECKOUT;
        HashMap<String, String> map = new HashMap<>();
        map.put("pay_id", pay_id + "");
        map.put("order_id", order_id );
        map.put("address_id", address_id );
        map.put("pre","0");
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            if (pay_name.equals("微信")) {
                HttpUtils.post(address, header, map, wxPayDataCallback);
            } else {
                HttpUtils.post(address, header, map, aliPayDataCallback);
            }
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            //ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    DirectBuyWXPayDataCallback wxPayDataCallback = new DirectBuyWXPayDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(DirectBuyWXPayData response, int id) {
            if(response.getData()!=null&&response.getData().getPaycode()!=null&&response.getData().getPaycode().getAppid()!=null){
                //微信支付发起
                IWXAPI iwxapi = WXAPIFactory.createWXAPI(mcontext, ConstantsUrl.WX_APPID, true);
                iwxapi.registerApp(ConstantsUrl.WX_APPID);
                PayReq req = new PayReq();
                req.appId = ConstantsUrl.WX_APPID;
                req.partnerId = response.getData().getPaycode().getPartnerid();
                req.prepayId = response.getData().getPaycode().getPrepayid();
                req.packageValue = response.getData().getPaycode().getWxpackage();
                req.nonceStr = response.getData().getPaycode().getNoncestr();
                req.timeStamp = response.getData().getPaycode().getTimestamp()+"";
                req.sign = response.getData().getPaycode().getSign();
                iwxapi.sendReq(req);
            }
        }
    };

    DirectBuyAliPayDataCallback aliPayDataCallback = new DirectBuyAliPayDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(DirectBuyAliPayData response, int id) {
            if (response.getData() != null && response.getData().getPaycode() != null) {
                final String orderInfo = response.getData().getPaycode();
                //支付宝支付发起
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(mcontext);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else {
                ObjectUtils.toast(mcontext, response.getMsg());
            }
        }
    };
}
